<template>
  <div>
    <!-- 云下载对话框 -->
    <el-dialog title="云下载" :visible.sync="downloadVisible" width="800px" append-to-body @close="closeDialog">
      <el-table :data="imgDownloadInfoList">
        <el-table-column label="缩略图" align="center" prop="imgPngPath" width="130">
          <template slot-scope="scope">
            <image-preview :src="scope.row.bucketUrl + scope.row.imgPngPath" />
          </template>
        </el-table-column>
        <el-table-column label="源类型" align="center" prop="imgType" width="60">
          <template v-slot="scope">
            <el-tag>{{ imgTypeMap[scope.row.imgType]}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="imgName" show-overflow-tooltip />
        <el-table-column label="源图片" align="center" >
          <template slot-scope="scope">
            <el-checkbox true-label="1" false-label="0" v-model="scope.row.imgSourceCheck" @change="imgChecked"/>
          </template>
        </el-table-column>
        <el-table-column label="JPG" align="center">
          <template slot-scope="scope">
            <el-checkbox true-label="1" false-label="0" v-model="scope.row.imgJPGCheck" @change="imgChecked"/>
          </template>
        </el-table-column>
        <el-table-column label="PNG" align="center">
          <template slot-scope="scope">
            <el-checkbox true-label="1" false-label="0" v-model="scope.row.imgPNGCheck" @change="imgChecked"/>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="imgStatus" width="55">
          <template v-slot="scope">
            <dict-tag :options="dict.type.sys_status" :value="scope.row.imgStatus"/>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" :disabled="multiple" @click="imgBatchDownload">批量下载</el-button>
        <el-button @click="closeDialog">关 闭</el-button>
      </div>
    </el-dialog>


    <el-drawer
      title="下载进度"
      :visible.sync="drawerOpen"
      :with-header="false"
      :modal="false"
      size="30%">
      <el-table :data="fileSelected">
        <el-table-column property="fileName" label="文件名称" align="center" show-overflow-tooltip />
        <el-table-column property="fileSize" label="大小" align="center" width="90">
          <template v-slot="scope">
            <span>{{ $fileSize(scope.row.fileSize) }}</span>
          </template>
        </el-table-column>
        <el-table-column property="progress" label="下载进度" align="center" width="300">
          <template slot="header">
            <div style="float: left;line-height: 35px;text-align: center;width: calc(100% - 30px);">下载进度</div>
            <el-tooltip class="item" effect="dark" content="清空已完成" placement="bottom">
              <el-button type="text" @click="deleteDownload" icon="el-icon-delete-solid" style="float: right;color: red;font-size: 18px;"></el-button>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-progress :percentage="scope.row.progress" :color="customColors" :status="scope.row.progressStatus" />
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <!-- 添加控制抽屉的图标按钮 -->
    <div class="drawer-control" @click="toggleDrawer">
      <i v-if="drawerOpen" class="el-icon-arrow-right drawer-icon"></i>
      <i v-else class="el-icon-download drawer-icon">
        <span v-if="activeDownloads > 0" class="download-badge">{{ activeDownloads }}</span>
      </i>
    </div>

  </div>
</template>

<script>
import { saveAs } from 'file-saver'
import { chunkDownloadFile } from '@/api/tool/minio'
export default {
  dicts: ['sys_status'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    imgList: {
      type: Array,
      default: () => []
    },
  },
  data() {
    return {
      // 非多个禁用
      multiple: true,
      // 弹出层状态
      downloadVisible: false,
      // 素材列表
      imgDownloadInfoList: [],
      // 抽屉弹出
      drawerOpen: false,
      // 判断鼠标移出屏幕右侧
      isMouseInArea: false,
      // 选中图片列表
      fileSelected: [],
      drawerVal: 0,
      imgTypeMap: {
        '1': 'PSD',
        '2': 'TIF',
        '3': 'TIFF',
        '4': 'CDR',
        '5': 'AI'
      },
      imgStatusMap: {
        'NORMAL': { text: '正常', type: 'success' },
        'DELETED': { text: '删除', type: 'danger' },
        'LOCKED': { text: '锁定', type: 'warning' }
      },
      // 进度条进度
      percentage: 0,
      // 进度条颜色
      customColors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
      // 新增：活动下载任务计数
      activeDownloads: 0
    }
  },
  watch: {
    visible(val) {
      this.downloadVisible = val
    },
    imgList(val) {
      this.imgDownloadInfoList = val.map(item => ({
        ...item,
        imgSourceCheck: '0',
        imgJPGCheck: '0',
        imgPNGCheck: '0'
      }))
    },
    // 监听下载任务变化更新计数
    fileSelected: {
      deep: true,
      handler(files) {
        this.activeDownloads = files.filter(f => f.progress < 100).length;
      }
    }
  },

  methods: {
    /** 弹窗关闭 */
    closeDialog() {
      this.$emit('close');
      this.downloadVisible = false
      this.imgDownloadInfoList = []
      this.multiple = true
    },
    /** 是否存在选则项 */
    imgChecked(){
      this.multiple = !this.imgDownloadInfoList.some(item => item.imgSourceCheck === '1' || item.imgJPGCheck === '1' || item.imgPNGCheck === '1');
    },
    /** 清空已下载完成 */
    deleteDownload(){
      this.fileSelected = this.fileSelected.filter(i => i.progress !== 100)
    },
    /** 批量下载 */
    imgBatchDownload() {
      if (!this.imgDownloadInfoList || this.imgDownloadInfoList.length === 0) {
        this.$modal.msgWarning("请选则下载项");
        return;
      }

      const selectedItems = this.imgDownloadInfoList.filter(item => item.imgSourceCheck === '1' || item.imgJPGCheck === '1' || item.imgPNGCheck === '1');

      if (selectedItems.length > 0) {
        const createFileObject = (item, extension, pathKey, sizeKey, replaceExtension = true) => ({
          fileName: replaceExtension ? `${item.imgName.replace(/\.[^.]*$/, '')}.${extension}` : item.imgName,
          filePath: item[pathKey],
          fileSize: item[sizeKey],
          progress: 0,
          progressStatus: undefined,
          complete: false, // 是否完成
        });
        const selected = selectedItems.flatMap(item => [
          ...(item.imgSourceCheck === '1' ? [createFileObject(item, 'source', 'imgSourcePath', 'imgSourceSize', false)] : []),
          ...(item.imgJPGCheck === '1' ? [createFileObject(item, 'jpg', 'imgJpgPath', 'imgJpgSize')] : []),
          ...(item.imgPNGCheck === '1' ? [createFileObject(item, 'png', 'imgPngPath', 'imgPngSize')] : [])
        ]);

        this.fileSelected = [...this.fileSelected, ...selected];
        this.downloadSelectedFiles(selected);
      }
    },
    /** 下载选中的文件 */
    async downloadSelectedFiles(selected) {
      const CHUNK_SIZE = 1024 * 1024 * 5
      // 遍历选中的，带着index序号
      for (const item of selected) {
        if (!item.complete){
          item.complete = true
          // 计算分片数量
          const totalChunks = Math.ceil(item.fileSize / CHUNK_SIZE);
          const offset =  0;
          const chunks = [];
          for (let i = offset + 1; i <= totalChunks; i++) {
            const start = CHUNK_SIZE * (i - 1);
            let end = CHUNK_SIZE * i - 1;
            if (end > item.fileSize ) {
              end = item.fileSize;
            }
            const res = await chunkDownloadFile(item, `bytes=${start}-${end}`);
            chunks.push(res);
            // 更新进度条进度
            const progress = Math.round((i / totalChunks) * 100);
            this.$set(item, 'progress', progress);
            if (progress === 100) {
              this.$set(item, 'progressStatus', 'success');
              // 更新活动任务计数
              this.activeDownloads = selected.filter(item => !item.complete).length;
            }
          }
          const blob = new Blob(chunks, { type: 'application/octet-stream' });
          this.saveAs(blob, decodeURIComponent(item.fileName))
        }
      }
    },
    saveAs(text, name, opts) {
      saveAs(text, name, opts);
    },
    toggleDrawer() {
      this.drawerOpen = !this.drawerOpen;
    },
  }

}

</script>

<style>
/* 添加控制按钮样式 */
.drawer-control {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  z-index: 2000;
  cursor: pointer;
  background-color: #fff;
  border-radius: 50% 0 0 50%;
  padding: 12px 6px 12px 12px;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
}

.drawer-control:hover {
  background-color: #f5f7fa;
}

.drawer-icon {
  font-size: 24px;
  color: #409EFF;
  position: relative;
}

.download-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}
</style>


